package com.onlyphoto.onlymall.mvp.view.fragment

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity.RESULT_OK
import android.content.ActivityNotFoundException
import android.content.ClipData
import android.content.Context.CLIPBOARD_SERVICE
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.base.BaseFragment
import com.onlyphoto.onlymall.mvp.contract.CWebView
import com.onlyphoto.onlymall.mvp.presenter.PWebViewImpl

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import androidx.annotation.RequiresApi
import com.google.gson.Gson
import com.onlyphoto.onlymall.BuildConfig
import com.onlyphoto.onlymall.bean.*
import com.onlyphoto.onlymall.mvp.view.activity.MainActivity
import com.onlyphoto.onlymall.mvp.view.activity.WebViewActivity
import com.onlyphoto.onlymall.utils.*
import com.onlyphoto.onlymall.widget.CommonDialog
import com.onlyphoto.onlymall.widget.ItemLongClickedPopWindow
import kotlinx.android.synthetic.main.fragment_webview.*
import me.bakumon.statuslayoutmanager.library.DefaultOnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.lang.ref.WeakReference


class WebViewFragment : BaseFragment<PWebViewImpl>(), CWebView.IVWebView, View.OnClickListener {

    private val fileChooseResultCode = 10000

    private val showDiaLog = 0
    private val noDiaLog = 1
    private var uploadMessage: ValueCallback<Uri>? = null
    private var uploadMessageAboveL: ValueCallback<Array<Uri?>>? = null
    var url: String? = null
    private var ua: String? = null
    private var downX: Int = 0
    private var imgurl: String? = null
    private var downY: Int = 0
    private var fileUri = ""
    //文件路径
    private var path: String? = null
    //文件名称
    private var fileName: String? = null
    private val mWebViewClient = MyWebViewClient(this@WebViewFragment)
    private var backFinish: Boolean = false

    private val processing = 100
    private var curProgress: Int = 0
    private var maxProgress: Int = 0
    private var flag: Boolean = false

    override fun retry() {
        showSuccess()
        web_view.reload()

    }

    override fun init() {
        title_text.text = arguments!!.getString(WebViewActivity.TAG_TITLE)

        iv_back.setOnClickListener(this)
        iv_close.setOnClickListener(this)
        url = arguments!!.get(WebViewActivity.TAG_URL) as String?

        setupWebView()

        web_view.loadUrl(url!!)

        builder = StatusLayoutManager.Builder(web_view)
                .setDefaultLoadingText("数据加载中...")
                .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                    override fun onCustomerChildClick(view: View) {
                        super.onCustomerChildClick(view)
                        when (view.id) {
                            R.id.ll_content -> {
                                when {
                                    view.tag === NetWorkStatus.FAIL -> retry()
                                    view.tag === NetWorkStatus.ERROR -> retry()
                                    view.tag === NetWorkStatus.EMPTY -> {
                                    }
                                }
                            }
                            else -> retry()
                        }
                    }
                })
                .setDefaultLayoutsBackgroundColor(R.color.white)
        statusLayoutManager = builder!!.build()
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.iv_back ->
                if (backFinish) {
                    goBack()
                } else {
                    if (web_view.canGoBack()) {
                        web_view.goBack()
                    } else {
                        goBack()
                    }
                }
            R.id.iv_close ->
                goBack()
        }
    }

    /**
     * 设置WebView
     */
    @SuppressLint("JavascriptInterface", "SetJavaScriptEnabled", "AddJavascriptInterface")
    private fun setupWebView() {
        web_view!!.scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY
        //WebView属性设置！！！
        val settings = web_view!!.settings
        settings.textZoom = 100
        settings.javaScriptEnabled = true
        settings.allowFileAccess = true
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        settings.domStorageEnabled = true
        settings.useWideViewPort = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        settings.loadWithOverviewMode = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.databaseEnabled = true
        ua = settings.userAgentString
        settings.userAgentString = settings.userAgentString + "/" + BuildConfig.USER_AGENT + "/" + BuildConfig.VERSION_NAME
        web_view.addJavascriptInterface(JavaMethod(), "nativeMethod")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            //CookieManager.getInstance().setAcceptThirdPartyCookies(web_view, true)
        }

        web_view.webChromeClient = object : WebChromeClient() {

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress != 100) {
                    progress_bar?.visibility = View.VISIBLE
                }
                maxProgress = newProgress
                myHandler!!.sendEmptyMessageDelayed(processing, 5)
            }

            override fun onReceivedTitle(view: WebView, title: String?) {
                super.onReceivedTitle(view, title)
                title_text?.text = title
            }

            //For Android  >= 4.1
            fun openFileChooser(valueCallback: ValueCallback<Uri>) {
                uploadMessage = valueCallback
                openImageChooserActivity()
            }

            override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri?>>?, fileChooserParams: FileChooserParams?): Boolean {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity()
                return true
            }
        }

        web_view.webViewClient = this.mWebViewClient

        web_view.setOnLongClickListener(View.OnLongClickListener { v ->
            val result = (v as WebView).hitTestResult ?: return@OnLongClickListener false
            val type = result.type
            if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
                return@OnLongClickListener false
            }
            if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
                //let TextViewhandles context menu return true;
            }
            val itemLongClickedPopWindow = ItemLongClickedPopWindow(activity, ItemLongClickedPopWindow.IMAGE_VIEW_POPUPWINDOW, ConvertUtil.dp2px(activity, 120f), ConvertUtil.dp2px(activity, 40f))
            // Setup custom handlingdepending on the type
            when (type) {
                WebView.HitTestResult.PHONE_TYPE -> {
                }
                WebView.HitTestResult.EMAIL_TYPE -> {
                }
                WebView.HitTestResult.GEO_TYPE -> {
                }
                WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
                }
                WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
                }
                WebView.HitTestResult.IMAGE_TYPE -> {
                    // 处理长按图片的菜单项
                    imgurl = result.extra
                    //通过GestureDetector获取按下的位置，来定位PopWindow显示的位置
                    itemLongClickedPopWindow.showAtLocation(v, Gravity.TOP or Gravity.LEFT, downX, downY + 10)
                }
                else -> {
                }
            }

            itemLongClickedPopWindow.getView(R.id.long_click_save_image)
                    .setOnClickListener {
                        itemLongClickedPopWindow.dismiss()
                        if (!TextUtils.isEmpty(imgurl)) {
                            try {
                                initImgFilePath()
                                Base64.decodeToFile(path + fileName, imgurl?.split(",".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()?.get(1))
                                ToastUtil.showToast("图片保存成功！")
                                val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                                val uri = Uri.fromFile(File(path + fileName))
                                intent.data = uri
                                activity!!.sendBroadcast(intent)
                            } catch (e: Exception) {
                                ToastUtil.showToast("图片保存失败！")
                                e.printStackTrace()
                            }

                        }
                    }
            true
        })
    }

    class MyWebViewClient(mWebViewFragment: WebViewFragment) : WebViewClient() {
        private val mFragment: WeakReference<WebViewFragment> = WeakReference(mWebViewFragment)

        @SuppressLint("AddJavascriptInterface")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            LogUtil.log("WebViewFragment", "shouldOverrideUrlLoading: $url")


            //处理跳转
            if (url.startsWith(SchemeTool.MyScheme)) {
                SchemeTool.jump(Uri.parse(url), mFragment.get()?.activity)
                return true
            }

            if (mFragment.get()?.parseScheme(url)!!) {
                val uri = Uri.parse(url)
                val intent = Intent(Intent.ACTION_VIEW, uri)
                mFragment.get()?.startActivity(intent)
                return true
            }

            try {
                if (url.startsWith("alipays://")) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    mFragment.get()?.startActivity(intent)
                    return true
                }
            } catch (e: Exception) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return true
            }

            if (url.contains("/recharge/pay?payId=1") ||
                    url.contains("https://mclient.alipay.com/cashier/mobilepay.htm")
                    || url.contains("https://openapi.alipay.com/gateway.do")) {
                return false
            }

            mFragment.get()?.web_view?.addJavascriptInterface(mFragment.get()?.JavaMethod()!!, "nativeMethod")
            view.loadUrl(url)
            return true
        }

        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            handler.proceed()  //接受所有证书
        }

        @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            super.onReceivedError(view, errorCode, description, failingUrl)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return
            }
            mFragment.get()?.showNetError()
        }

        @TargetApi(Build.VERSION_CODES.M)
        override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
            LogUtil.log("","onReceivedError error" + error?.errorCode + "，，" + error?.description)
            if (request?.isForMainFrame == true && -6 != error?.errorCode) {
                mFragment.get()?.showNetError()
            }
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            LogUtil.log("","mFragment.get()" + mFragment.get())
            mFragment.get()?.onPageFinishedShow(view)
            if (mFragment.get()?.flag!!) {
                mFragment.get()?.myHandler?.removeCallbacksAndMessages(null)
            }
        }
    }

    fun onPageFinishedShow(view: WebView) {
        if (view.canGoBack()) {
            iv_close?.visibility = View.VISIBLE
        } else {
            iv_close?.visibility = View.GONE
        }

        if (view.url!!.contains("pop_back")) {
            backFinish = true
        }
    }

    fun parseScheme(url: String): Boolean {
        return url.contains("platformapi/startApp")
    }

    override fun getLayoutRes(): Int {
        return R.layout.fragment_webview
    }

    override fun createPresenter() {
        mPresenter = PWebViewImpl(mContext, this)
    }

    override fun showLoading() {}

    override fun hideLoading() {}

    companion object {
        /**
         * 创建LoanWebViewFragment对象
         *
         * @param bundle Bundle
         * @return WebViewFragment
         */
        fun newInstance(bundle: Bundle): WebViewFragment {
            val fragment = WebViewFragment()
            fragment.arguments = bundle
            return fragment
        }

        fun newInstance(): WebViewFragment {
            val fragment = WebViewFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }

        /**
         * 创建Bundle
         *
         * @param title      标题
         * @param url        链接地址
         * @param isPush     是否推送
         * @param jumpToHome 跳转到首页
         * @return
         */
        fun makeBundle(title: String?, url: String, isPush: Boolean, jumpToHome: String?): Bundle {
            val bundle = Bundle()
            bundle.putString(WebViewActivity.TAG_TITLE, title)
            bundle.putString(WebViewActivity.TAG_URL, url)
            bundle.putBoolean(WebViewActivity.TAG_IS_PUSH, isPush)
            bundle.putString(WebViewActivity.TAG_JUMP_TO_HOME, jumpToHome)
            return bundle
        }
    }

    inner class JavaMethod {

        @JavascriptInterface
        fun returnNativeMethod(typeStr: String) {
            LogUtil.log("===", "typeStr:$typeStr")
            val bean = Gson().fromJson(typeStr, WebViewJSBean::class.java)
            val type = bean.type

            if (!TextUtils.isEmpty(bean.skipCode)) {
                activity!!.runOnUiThread {
                    if (SchemeTool.TAG_JUMP_H5 == bean.skipCode) {
                        SchemeTool.jump(Uri.parse(bean.url), activity)
                    } else {
                        SchemeTool.jump(Uri.parse(SchemeTool.MyScheme + "://?skipCode=" + bean.skipCode), activity)
                    }
                }
                return
            }
            if ("0" == type) {
                goBack()
            } else if ("5" == type) {
                if ("1" == bean.isHelp) {
                    activity!!.runOnUiThread {
                        title_right_text.visibility = View.VISIBLE
                        title_right_text.text = "帮助"
                        title_right_text.setOnClickListener {
                        }
                    }
                } else {
                    activity!!.runOnUiThread {

                    }
                }
            }
        }

        @SuppressLint("ObsoleteSdkInt")
        @JavascriptInterface
        fun copyTextMethod(text: String) {
            val bean = Gson().fromJson(text, CopyTextBean::class.java)
            val c = activity!!.getSystemService(CLIPBOARD_SERVICE) as android.content.ClipboardManager
            c.setPrimaryClip(ClipData.newPlainText("text", bean.text))
            ToastUtil.showToast(bean.tip)
        }

        @JavascriptInterface
        fun callPhoneMethod(tele: String) {
            CommonDialog.newInstance().setDialogType(false, false).setMessage("呼叫$tele").setOkBtn("呼叫") {
                call(tele)
            }.setCancelBtn("取消") {}.show(activity!!.supportFragmentManager, "callPhone", true)
        }

        @JavascriptInterface
        fun shareMethod(shareBean: String) {
            LogUtil.log("shareMethod", "===$shareBean")
            val bean = Gson().fromJson(shareBean, WebShareBean::class.java)
            //QQ、QZONE、WEIXIN、WEIXIN_CIRCLE
            if (bean != null) {
                when {
                    bean.type == 1 -> activity!!.runOnUiThread {
                        title_right_text.text = "分享"
                        title_right_text.setOnClickListener {
                        }
                    }
                    bean.type == 0 -> activity!!.runOnUiThread {  }
                    bean.type == 2 -> activity!!.runOnUiThread {  }
                }
            }
        }

        @JavascriptInterface
        fun checkAppIsInstalled(url: String): Boolean {
            val uri = Uri.parse(url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            val componentName = intent.resolveActivity(context!!.packageManager)
            return componentName != null
        }

        @JavascriptInterface
        fun hideTitle(hide: Int) {
            LogUtil.log("", "hide=$hide")
            if (1 == hide) {
                activity!!.runOnUiThread {
                    rl_title.visibility = View.GONE
                }
            } else {
                activity!!.runOnUiThread {
                    rl_title.visibility = View.VISIBLE
                }
            }

        }
    }

    private fun checkSD(): Boolean {
        return if (android.os.Environment.getExternalStorageState() == android.os.Environment.MEDIA_MOUNTED) {
            true
        } else {
            ToastUtil.showToast("SD卡不存在！")
            false
        }

    }


    private fun openImageChooserActivity() {
        try {
            val intent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)

            if (intent.resolveActivity(activity!!.packageManager) == null) {
                ToastUtil.showToast("无法打开系统相册")
            } else {
                startActivityForResult(intent, fileChooseResultCode)
            }
        } catch (e: ActivityNotFoundException) {
            ToastUtil.showToast("无法打开系统相册")
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == fileChooseResultCode) {
            if (null == uploadMessage && null == uploadMessageAboveL) return
            var result: Uri? = if (data == null || resultCode != RESULT_OK) {
                null
            } else {
                data.data
            }

            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage!!.onReceiveValue(result);
                uploadMessage = null
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun onActivityResultAboveL(requestCode: Int, resultCode: Int, intent: Intent?) {
        if (requestCode != fileChooseResultCode || uploadMessageAboveL == null)
            return
        var results: Array<Uri?>? = null
        if (resultCode == RESULT_OK) {
            if (intent != null) {
                val dataString = intent.dataString
                val clipData = intent.clipData
                if (clipData != null) {
                    results = arrayOfNulls(size = clipData.itemCount)

                    for (i in 0 until clipData.itemCount) {
                        val item = clipData.getItemAt(i)
                        results[i] = item.uri

                    }
                }
                if (dataString != null)
                    results = arrayOf(Uri.parse(dataString))
            }
        }
        uploadMessageAboveL!!.onReceiveValue(results)
        uploadMessageAboveL = null
    }

    fun goBack() {
        when {
            "1" == arguments!!.getString(WebViewActivity.TAG_JUMP_TO_HOME) -> {
                val intent = Intent(activity, MainActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                startActivity(intent)
                activity!!.finish()
            }
            "2" == arguments!!.getString(WebViewActivity.TAG_JUMP_TO_HOME) -> {
                //确认订单界面跳转到商城首页
                val intent = Intent(activity, MainActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                startActivity(intent)

                var banner = HomePageBean.Banner("",0,"")
                banner.skipCode = "115_index"
                EventBus.getDefault().post(banner)
                activity!!.finish()
            }
            else -> activity!!.finish()
        }

    }

    fun onBackPressed() {
        if (web_view.canGoBack()) {
            web_view.goBack()
        } else {
            goBack()
        }
    }

    override fun onDestroy() {
        //webView 内存泄漏解决
        if (web_view != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码
            // 需要先onDetachedFromWindow()，再destroy()
            val parent = web_view.parent
            if (parent != null) {
                (parent as ViewGroup).removeView(web_view)
            }
            web_view.stopLoading()
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            web_view.settings.javaScriptEnabled = false
            web_view.clearHistory()
            web_view.loadUrl("about:blank")
            web_view.removeAllViews()
            web_view.destroy()
        }
        super.onDestroy()
    }

    private fun initImgFilePath() {
        path = AndroidUtils.sdCardPath + "/" + activity!!.applicationInfo.packageName + "/"
        val file = File(path)
        if (!file.exists())
            file.mkdirs()
        fileName = System.currentTimeMillis().toString() + ".jpg"
        fileUri = "file://$path$fileName"
    }

    fun call(tel: String) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel.replace("-".toRegex(), "").trim { it <= ' ' }))
        startActivity(intent)
    }

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    fun showNetError() {
        if (activity?.isFinishing != false) {
            return
        }
        commonStatusView!!.setContent(R.mipmap.no_network, "网络出错~", "点击刷新")
        commonStatusView!!.setType(NetWorkStatus.ERROR)
        showCustomLayout(commonStatusView!!, R.id.tv_next_step)
    }

    private var myHandler: MyHandler? = MyHandler(this)

    private class MyHandler(fragment: WebViewFragment) : Handler() {
        private var mFragment: WeakReference<WebViewFragment> = WeakReference(fragment)

        override fun handleMessage(msg: Message) {
            var curProgress: Int? = mFragment.get()?.progress_bar?.progress
            if (curProgress != null) {
                if (curProgress < mFragment.get()?.maxProgress!!){
                    mFragment.get()?.progress_bar?.progress = curProgress.inc()
                    mFragment.get()?.processing?.let { mFragment.get()?.myHandler?.sendEmptyMessageDelayed(it, 5) }
                } else {
                    mFragment.get()?.progress_bar?.progress = curProgress
                }
            }
            if (curProgress == 100) {
                mFragment.get()?.myHandler?.removeCallbacksAndMessages(null)
                mFragment.get()?.progress_bar?.progress = 0
                mFragment.get()?.progress_bar?.visibility = View.GONE
                mFragment.get()?.flag = true
            }
        }
    }
}
